package com.dao;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    public BaseDao(){}
    //加载程序
    static {
        BaseDao baseDao=new BaseDao();
        baseDao.getConfig();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    private static void getConfig(){
        Properties properties = new Properties();
        String path = "jdbc.properties";
        InputStream ins= BaseDao.class.getClassLoader().getResourceAsStream(path);
        try {
            properties.load(ins);

        } catch (Exception e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("jdbc.dri");
        url = properties.getProperty("jdbc.url");
        username = properties.getProperty("jdbc.username");
        password = properties.getProperty("jdbc.password");

    }
    public static  Connection getConn() {
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException("Failed to establish database connection.", e);
        }
    }

    public static int ExcuteUpdate(String sql,Object...objects){
        try(Connection conn=getConn();
            PreparedStatement stmt=conn.prepareStatement(sql)) {
            for (int i = 0; i < objects.length; i++) {
                stmt.setObject(i+1, objects[i]);
            }
            return stmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to execute SQL update statement.", e);
        }
    }
    public static boolean Login(String sql,Object...objects){
        try(Connection conn=getConn();
            PreparedStatement stmt=conn.prepareStatement(sql)) {
            for (int i = 0; i < objects.length; i++) {
                stmt.setObject(i+1, objects[i]);
            }
            if(stmt.executeQuery().next()){
                return true;
            }else {
                return false;
            }

        } catch (SQLException e) {
            throw new RuntimeException("Failed to execute SQL update statement.", e);
        }
    }

    public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }

            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }

            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException var5) {
            var5.printStackTrace();
        }
    }
}
